<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./matter.js"></script>
</head>

<body>
  <div id="c"></div>
  <script>
    const Engine = Matter.Engine
    const Render = Matter.Render
    const Bodies = Matter.Bodies
    const Composite = Matter.Composite
    const Runner = Matter.Runner

    let engine = Engine.create()
    let render = Render.create({
      element: document.getElementById('c'), // 绑定页面元素
      engine, // 绑定引擎
      options: {
        wireframes: false
      }
    })
    // 创建鼠标实例
    let mouse = Matter.Mouse.create(render.canvas)
    // 给鼠标添加约束
    let mouseConstraint = Matter.MouseConstraint.create(engine, {
      mouse: mouse,
      constraint: {
        stiffness: 0.2,
        render: {
          visible: false // 默认为 true，会显示鼠标拖拽轨迹
        }
      }
    })

    // 5-1. 创建两个正方形
    let boxA = Bodies.rectangle(80, 40, 80, 80, { // x,y,w,h
      frictionAir: 0, // 设置空气阻力
      restitution: 0.5, // 弹力
      mass: 0.1 //质量
    })
    let boxB = Bodies.rectangle(450, 40, 80, 80, {
      frictionAir: 0, // 设置空气阻力
      restitution: 0.5, // 弹力
      mass: 0.2 //质量
    })

    let stack = Matter.Composites.stack(200, 20, 6, 3, 10, 20, function (x, y) {
      return Matter.Bodies.circle(x, y, 16, {
        angle: Math.PI / 180 * 30, // 旋转30度
        restitution: 0.8 // 添加一点回弹力
      })
    })

    // 5-2. 创建地面，将isStatic设为true，表示物体静止
    let ground = Bodies.rectangle(400, 610, 810, 60, {
      isStatic: true,
      render: {
        fillStyle: '#FFA327'
      }
    })
    // 5-2. 创建墙面，将isStatic设为true，表示物体静止
    let wall1 = Bodies.rectangle(10, 300, 50, 500, {
      isStatic: true,
      render: {
        fillStyle: '#FFA327'
      }
    })
    // 5-2. 创建墙面，将isStatic设为true，表示物体静止
    let wall2 = Bodies.rectangle(800, 300, 50, 500, {
      isStatic: true,
      render: {
        fillStyle: '#FFA327'
      }
    })

    // 板子A（红色）
    let rectA = Matter.Bodies.rectangle(200, 330, 20, 100, {
      isStatic: true,
      render: {
        fillStyle: '#f00'
      },
      collisionFilter: {
        group: -1
      }
    })

    // 板子B（蓝色）
    let rectB = Matter.Bodies.rectangle(200, 330, 200, 20, {
      render: {
        fillStyle: '#00f'
      },
      collisionFilter: {
        group: -1
      }
    })

    // 创建旋转约束
    let rotateConstraint = Matter.Constraint.create({
      bodyA: rectA,
      bodyB: rectB,
      length: 0
    })



    // 6. 将所有物体添加到世界中
    Composite.add(engine.world, [stack, ground, wall1, wall2, rectA, rectB, rotateConstraint, mouseConstraint])

    // 7. 执行渲染操作
    Render.run(render)

    // 8. 创建运行方法
    var runner = Runner.create()

    // 9. 运行渲染器
    Runner.run(runner, engine)
  </script>
</body>

</html>